<?php

    namespace app\api\controller;
    use app\common\controller\Base;
    use think\Db;
    use think\Exception;
    use think\Model;
    use yaliSDK\utils\WXHelper;

    class Api extends Base{
        protected $data = [];
        protected $valid_time=15;//验证码过期时间
        protected $end_time=6*3600;//初始化结束时间 6小时
        protected $liveSet='LiveSet';
        protected $liveAppid = '1251193325';//腾讯直播Appid 
        protected $jl_key = '27ba3583e82daaee64256d750cec8115';//腾讯直播鉴流Key
        protected $api_url = "http://fcgi.video.qcloud.com/common_access";//腾讯云直播API调用地址

        /*
         *  暂停推流并延迟回复
         *  action 参数 forbid = 断流  resume = 恢复推流
         *  abstime_end 参数  禁播截止的绝对时间，请填写UNIX 时间戳（十进制），系统最多禁播三个月。
         */
        public function channel_manager($channel_id = '',$action = 'forbid'){
            $t = time()+300;$sign = md5($this->jl_key.$t);
            $param = ['appid'=>$this->liveAppid,'interface'=>'channel_manager','t'=>$t,'sign'=>$sign,'Param.s.channel_id'=>$channel_id,'Param.n.abstime_end'=>(time()+180),'Param.s.action'=>$action];
            $result_json = $this->api_http($this->api_url,$param,'GET');
            $result_arr = json_decode($result_json, true);
            return $result_arr;
        }

        /*
         *  定时开启-已关闭直播流
         */
        public function timing_openChannel(){
            //获取已关闭的直播流列表
            $close_list = $this->channel_list(3);
            if(!empty($close_list)){
                if($close_list['all_count']>0){
                    $str = '';$result_str = '';$i = 0;
                    foreach ($close_list['channel_list'] as $key => $value) {
                        $res = $this->change_channel_status(1,$value['channel_id']);
                        if($res['ret']==0){
                            $str = '成功<br/>';
                        }else{
                            $str = '<span style="color:red">失败</span><br/>';
                            $info['type'] = 9;
                            $info['error_msg'] = '腾讯接口：开启ChannelID:'.$value['channel_id'].'失败。';
                            $info['table_name'] = 'yali_live';
                            $info['table_id'] = $value['channel_id'];
                            $info['addtime'] = time();
                            $table_obj->name('ErrorLog')->add($info);
                        }
                        $result_str.= "ChannelID:".$value['channel_id']."处理".$str;
                        $i++;
                    }
                }else{
                    $result_str = '暂无需处理数据';
                }
            }
            return $result_str;
            
        }

        /*
         *  查询频道列表
         *  status   0：表示断流，1：表示开启，3：表示关闭
         */
        public function channel_list($status=0){
            $t = time()+3600;$sign = md5($this->jl_key.$t);
            $param = ['appid'=>$this->liveAppid,'interface'=>'Live_Channel_GetChannelList','t'=>$t,'sign'=>$sign,'Param.n.status'=>$status,'Param.n.page_size'=>10,'Param.n.page_no'=>1];
            $result_json = $this->api_http($this->api_url,$param,'GET');
            $result_arr = json_decode($result_json, true);
            if(!empty($result_arr['output'])){
                return $result_arr['output'];
            }else{
                return '暂无数据';
            }
        }

        /*
         * 修改直播房间ID的状态 
         * 0 表示禁用，1 表示允许推流，2 表示断流   
         */
        public function change_channel_status($status = 0,$channel_id = ''){
                $t = time()+1800;$sign = md5($this->jl_key.$t);
            $param = ['appid'=>$this->liveAppid,'interface'=>'Live_Channel_SetStatus','t'=>$t,'sign'=>$sign,'Param.s.channel_id'=>$channel_id,'Param.n.status'=>$status];
            $result_json = $this->api_http($this->api_url,$param,'GET');
            $result_arr = json_decode($result_json, true);
            return $result_arr;
        }

        /*
         * 定时查询直播间是否直播中
         */
        public function check_onlive(){
            $now_time = time();
            $table_obj = Db::connect(config('database.db_config1'));
            $list = $table_obj->name('Live')->field(['id','title','current_id','current_room','end_time'])->where(['current_id'=>['neq','']])->select();   
            if($list){
                $result_str = '';$i = 0;
                $t = time()+3600;$sign = md5($this->jl_key.$t);
                foreach ($list as $key => $value) {
                    $param = ['appid'=>$this->liveAppid,'interface'=>'Live_Channel_GetStatus','t'=>$t,'sign'=>$sign,'Param.s.channel_id'=>$value['current_id']];
                    $result_json = $this->api_http($this->api_url,$param,'GET');
                    $result_arr = json_decode($result_json, true);
                    //print_r($value);exit;
                    if($result_arr['output'][0]['status']!=1){//查询为 断流状态/关闭状态 则清空此状态
                        $table_obj->name('Live')->where('id',$value['id'])->update(['current_id'=>'','current_room'=>NULL]);
                        if($table_obj!==false){
                            $str = '成功<br/>';
                        }else{
                            $str = '<span style="color:red">失败</span><br/>';
                            $info['type'] = 9;
                            $info['error_msg'] = '更新正在直播中状态失败';
                            $info['table_name'] = 'yali_live';
                            $info['table_id'] = $value['id'];
                            $info['addtime'] = $now_time;
                            $table_obj->name('ErrorLog')->add($info);
                        }
                        $result_str.= "ID:".$value['id']."处理".$str;
                        $i++;
                    }
                }
                $result_str = ($i==0?'暂无需处理数据':$result_str);

            }else{
                $result_str = '暂无需处理数据';
            }
            return $result_str;
        }

        /*
         * 定时检测直播计划是否过期
         * 到期修改为已结束 定时任务每10分钟处理一次
         */
        public function check_expire(){
            $now_time = time();
            $table_obj = Db::connect(config('database.db_config1'));
            $list = $table_obj->name('Live')->field(['id','start_time','end_time','current_id'])->where(['status'=>1,'end_time'=>['lt',$now_time]])->order('addtime desc')->select();
            if($list){
                $result_str = '';
                foreach ($list as $key => $value) {
                    $result_arr = $this->channel_manager($value['current_id']);
                    if(isset($result_arr['ret'])){
                        if($result_arr['ret'] != 0){
                            $str = '<span style="color:red">失败</span><br/>';
                            $info['error_msg'] = '断流失败，返回错误码'.$result_arr['retcode'];
                        }
                    }
                    $res = $table_obj->name('Live')->where(['id'=>$value['id']])->update(['status'=>2,'current_id'=>'','current_room'=>NULL,'live_end_time'=>time()]);
                    if($res>0){
                        $str = '成功<br/>';
                    }else{
                        $str = '<span style="color:red">失败</span><br/>';
                        $info['error_msg'] = '更新live表状态失败';
                    }
                    if(!empty($info)){
                        $info['type'] = 9;
                        $info['table_name'] = 'yali_live';
                        $info['table_id'] = $value['id'];
                        $info['addtime'] = $now_time;
                        $table_obj->name('ErrorLog')->add($info);
                    }
                    $result_str.= "ID:".$value['id']."处理".$str;
                }
                return $result_str;
            }else{
                return '暂无需处理数据';
            }
        }

        public function getWxOpenId(){
            $data = $this->data;
            $check = $this->validate($data,'code.code');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $WX_SET=WXHelper::getWXSetByAppId($data['appid']);
            if(!empty($WX_SET)){
                $handler =  new \app\auth\model\AppletBase(['appid'=>$WX_SET['WX_APPID'],'appsecret'=>$WX_SET['WX_APPSECRET']]);
                $result=$handler->getWxOpenId($data['wx_code']);
                if ($result && !empty($result->errcode)) {
                    return api_return('-23034', $result);
                } else {
                    return api_return('10603', $result);
                }
            }else{
                return api_return('-50038');
            }
        }

        public function getOpenId(){
            $data = $this->data;
            $check = $this->validate($data, 'anchor.mobile');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $result = Model('Api')->takeOpenIdOfMobile($data);
            if ($result !== false) {
                return api_return('10603', $result);
            } else {
                return api_return('-10682', $result);
            }
        }


        public function deleteAnchor(){
            $data = $this->data;
            $check = $this->validate($data, 'anchor.delete');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $result = Model('Api')->delAnchor($data);
            if ($result !== false) {
                return api_return('10603', $result);
            } else {
                return api_return('-10682', $result);
            }
        }


        public function saveAnchor(){
            $data = $this->data;
            $check = $this->validate($data,'anchor.anchor');
            if (TRUE !== $check) {
                return api_return($check);
            }
           $result = Model('Api')->saveAnchor($data);
            //添加主播成功，生成个人二维码
            if ($result !== false) {
                $WX_SET=!empty($data['appid'])?WXHelper::getWXSetByAppId($data['appid']):'';
                    if(empty($data['id'])&&!empty($data['appid']) && $result) {
                        if (!empty($WX_SET)) {
                            $param = [
                                ['uid' => $result]
                            ];
                            $handler = new \app\auth\model\AppletBase(['appid' =>$WX_SET['WX_APPID'], 'appsecret' =>$WX_SET['WX_APPSECRET']]);
                            $f = $handler->create_qrcode_batch($param);
                            if (!empty($f)) {
                                $res = Db::connect(config('database.db_config1'))->name('Anchor')->where(['id' => $result])->update(['qr_code' => $f[0]]);
                                if ($res == false) {
                                    return api_return('-50039',$result);
                                }else{
                                    $p=[
                                       'id'=> $result,
                                        'qr_code'=>$f[0]
                                    ];
                                    return api_return('10603',$p);
                                }
                            } else {
                                return api_return('-50040',$result);
                            }
                        }else{
                            return api_return('-50041',$result);
                        }
                    }else{
                       return api_return('10603', $result);
                    }
            } else {
                return api_return('-10682', $result);
            }
        }

        //发送手机验证码
        public function sendMobileCode(){
            $data = $this->data;
            $check = $this->validate($data, 'code.send_code_single_mobile');
            if (TRUE !== $check) {
                return api_return($check);
            } else {
                return api_return(\app\common\model\Base::sendCode($data));
            }
        }

        //更换绑定手机
         public function updataMobile(){
            $data=$this->data;
             $check = $this->validate($data, 'code.updata_mobile');
             if (TRUE !== $check) {
                 return api_return($check);
             }

             $get_one=Db::connect(config('database.db_config1'))->name('SmsCheckCode')->where(['val'=>$data['mobile'],'uid'=>'0','code'=>md5($data['code'])])->order('addtime desc')->find();
             if(!empty($get_one)){
                 $f=$get_one['addtime'] +$this->valid_time*60;
                 if(time() > $f){
                     return api_return('-10679');
                 }
                 $check_is_bang_phone =Db::connect(config('database.db_config1'))->name('anchor')->where(['mobile'=>$data['mobile'],'status'=>['neq',-1]])->count();
                 if($check_is_bang_phone>1){
                     return api_return('-10748');
                 }
                 $get_user=Db::connect(config('database.db_config1'))->name('anchor')->where(['id'=>$data['uid'],'status'=>['neq',-1]])->value('id');
                 if(empty($get_user)){
                     return api_return('-11599');
                 }
                 $result = Model('Api')->updataMobile($data);
                 if ($result !== false) {
                     return api_return('10603', $result);
                 } else {
                     return api_return('-10682', $result);
                 }
             }else{
                 return api_return('-10667');
             }
         }
        
        //绑定手机号码和openId
        public function bandMobileCode(){
            $data = $this->data;
            $check = $this->validate($data, 'code.check_code_mobile');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $get_one=Db::connect(config('database.db_config1'))->name('SmsCheckCode')->where(['val'=>$data['mobile'],'uid'=>'0','code'=>md5($data['code'])])->order('addtime desc')->find();
            if(!empty($get_one)){
                $f=$get_one['addtime'] +$this->valid_time*60;
                if(time() > $f){
                    return api_return('-10679');
                }
             $check_is_bang_phone =Db::connect(config('database.db_config1'))->name('anchor')->where(['mobile'=>$data['mobile'],'status'=>['neq',-1]])->count();
                if($check_is_bang_phone>1){
                    return api_return('-10748');
                }
                $get_user=Db::connect(config('database.db_config1'))->name('anchor')->where(['id'=>$data['uid'],'status'=>['neq',-1]])->value('id');
                if(empty($get_user)){
                    return api_return('-11599');
                }
                $result = Model('Api')->bandMobile($data);
                if ($result !== false) {
                    return api_return('10603', $result);
                } else {
                    return api_return('-10682', $result);
                }
            }else{
                return api_return('-10667');
            }
        }


        //绑定手机和openid并 注册
        public function bandMobileRegister(){
            $data = $this->data;
          //  $check = $this->validate($data, 'code.check_register_mobile');
            $check = $this->validate($data, 'code.check_register_mobile_nocode'); //验证码非必要
            if (TRUE !== $check) {
                return api_return($check);
            }
                if(!empty($data['code'])){
                    $get_one=Db::connect(config('database.db_config1'))->name('SmsCheckCode')->where(['val'=>$data['mobile'],'uid'=>'0','code'=>md5($data['code'])])->order('addtime desc')->find();
                    if(!empty($get_one)){
                        $ex_time =$get_one['addtime'] +$this->valid_time*60;
                        if(time() > $ex_time){
                            return api_return('-10679');
                        }
                    }else{
                        return api_return('-10647');
                    }
                }

                $check_is_bang_phone =Db::connect(config('database.db_config1'))->name('anchor')->where(['mobile'=>$data['mobile']])->count();
                if($check_is_bang_phone>=1){
                    return api_return('-10748');
                }
                $result = Model('Api')->bandUser($data);
                if ($result !== false) {
                    //初始化一个直播计划
//                    try{
                        $reg=$this->setWebProduct($data['name'],$result);
                        Model('AnchorProduct')->saveLive($reg['pant'],$reg['produt_list']);

//                    }catch (\Exception $e){
//
//                    }
                    return api_return('10603', $result);
                } else {
                    return api_return('-10682', $result);
                }

        }


        //登录
        public function login(){
            $data = $this->data;
            $check = $this->validate($data, 'code.login');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $check_is_bang =Db::connect(config('database.db_config1'))->name('Anchor')->where(['mobile'=>$data['mobile'],'status'=>1])->find();
            if(!$check_is_bang['open_id'] && !$check_is_bang){
                //不存在数据的时候 添加
                $result = Model('Api')->bandUser($data);
                if ($result !== false) {
                    //初始化一个直播计划
                    try{
                        $reg=$this->setWebProduct($data['name'],$result);
                        Model('AnchorProduct')->saveLive($reg['pant'],$reg['produt_list']);
                    }catch (\Exception $e){

                    }
                    return api_return('10603', $result);
                } else {
                    return api_return('-10682', $result);
                }
            }else{
                //如果存在数据，但是不存在openId
                    if($check_is_bang && !$check_is_bang['open_id']){
                     $result =Db::connect(config('database.db_config1'))->name('Anchor')->where(['id'=>$check_is_bang['id']])->update(['open_id'=>$data['openId']]);
                        if($result!==false){
                            //检测是否存在计划和数据
                           $get_live= Db::connect(config('database.db_config1'))->name('Live')->where(['anchor_id'=>$check_is_bang['id']])->find();
                            if(!$get_live){
                                $reg=$this->setWebProduct($data['name'],$result);
                                Model('AnchorProduct')->saveLive($reg['pant'],$reg['produt_list']);
                                if($res!==false){
                                    return api_return('10603', $res);
                                }else{
                                    return api_return('-10682', $res);
                                }
                            }else{
                                return api_return('10603', $result);
                            }

                        }else{
                            return api_return('-10682', $result);
                        }
                    }
            }
        }


        //生成小程序二维码
        public function getTwoDimensionPic(){
            $data = $this->data;
            $token =config('wechat_live');
            $upload_handler =  new \app\auth\model\AppletBase(['appid'=>$token['app_id'],'appsecret'=>$token['secret']]);
            $param=[
               'small_pic'=>'1',
            ];
           $f=$upload_handler ->create_qrcode_batch($param);
           if(!empty($f)){
               return api_return('10603', $f);
           }else{
               return api_return('-10682');
           }
        }

        //获取直播计划信息列表
        public function getLiveList(){
            $data =$this->data;
            $result = Model('AnchorProduct')->getLiveList($data);
            if($result !== false){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }

        //获取主播列表
        public function anchorList(){
            $data =$this->data;
            $result = Model('AnchorProduct')->getAnchorList($data);
            if(!empty($result)){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }

        //添加編輯直播計劃
        public function saveLivePlan(){
                $product_list=[];
                $data=$this->data;
                if(empty($data)){
                    return api_return('-50022');
                }
            if(!empty($data['product_id_list'])){
                try{
                    $product_list=explode(',',$data['product_id_list']);
                }catch (\Exception $e){
                    return api_return('-50027');
                }
            }
            //添加
            if(empty($data['id'])){
                if(empty($data['title'])){
                    return api_return('-50011');
                }
                if(!isset($data['uid'])){
                    return api_return('-50023');
                }
                if(empty($data['anchor_id'])){
                    return api_return('-50014');
                }
                if(empty($data['start_time'])){
                    return api_return('-50015');
                }
                if(empty($data['end_time'])){
                    return api_return('-50016');
                }
                
                if($data['start_time']>=$data['end_time']){
                    return api_return('-50007');
                }
                if(empty($data['product_id_list'])){
                  return api_return('-50028');
                }

                //检测该时间段，该直播是否正在直播
                $check_anchor=   $check_anchor=Db::connect(config('database.db_config1'))->name('Live')->where(' '.$data['start_time'].' between `start_time` and `end_time`')->where(['status'=>['in','o,1'],'anchor_id'=>$data['anchor_id']])->find();
                if(!empty($check_anchor)){
                    return api_return('-50020');
                }
            }
            $validate_name= !empty($data['id'])?'live.save':'live.add';
            $check = $this->validate($data,$validate_name);
            if (TRUE !== $check) {
                return api_return($check);
            }
            unset($data['product_id_list']);
            $result = Model('AnchorProduct')->saveLive($data,$product_list);
            if($result !== false){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }

      //删除计划
        public function deleteLivePlan(){
            $data=$this->data;
            //如果存在ID修改 否则添加
            $check = $this->validate($data, 'Live.delete_live');
            if (TRUE !== $check) {
                return api_return($check);
            }
           $check_is_start=Db::connect(config('database.db_config1'))->name('Live')->where(['id'=>$data['id'],'status'=>1])->value('id');
            if(!empty($check_is_start)){
                return api_return(	-50024);
            }
           $result = Model('AnchorProduct')->deleteLive($data);
            if($result !== false){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }


      //主播获取粉丝列表
        public function getLiveFollowList(){
            $data=$this->data;
            $check = $this->validate($data, 'Anchor.follow');
            if (TRUE !== $check) {
                return api_return($check);
            }
            $result = Model('AnchorProduct')->liveFollowList($data);
            if($result !== false){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }

        //获取直播端默认入口页
        public function getLivePage(){
            $result=Db::connect(config('database.db_config1'))->name($this->liveSet)->where(['is_use'=>1])->select();
            if($result !== false){
                return api_return('10603', $result);
            }else{
                return api_return('-10682');
            }
        }

        //修改直播端默认入口页
        public function saveLivePage(){
            $data=$this->data;
            if(!isset($data['is_page'])){
                return api_return('-50044');
            }
            if(!isset($data['id'])){
                return api_return('-50045');
            }
            $get_one=Db::connect(config('database.db_config1'))->name($this->liveSet)->where(['is_use'=>1])->find();
            if(!empty($get_one)){
                $result=Db::connect(config('database.db_config1'))->name($this->liveSet)->where(['id'=>$data['id']])->update($data,Db::connect(config('database.db_config1'))->name($this->liveSet)->where(['is_use'=>1])->getTableFields());
                if($result !== false){
                    return api_return('10603', $result);
                }else{
                    return api_return('-10682');
                }
            }else{
                return api_return('-50046');
            }
        }

        //转换第三方知乎API
        public  function transformApi(){
            $data=$this->data;
            $header=array('Content-Type'=>'application/json');
            $url='';
            if(!empty($data['latest'])){ //最新列表
                $url ='https://news-at.zhihu.com/api/4/news/latest';
            }
            if(!empty($data['before'])){ //之前列表
                $url ='https://news.at.zhihu.com/api/4/news/before/'.$data['time'];
            }
            if(!empty($data['detail'])){ //详细页
                $url ='https://news-at.zhihu.com/api/4/news/'.$data['id'];
            }
            $result= $this->api_http($url,$data,'get',$header);
            if($result !== false){
                return api_return('10603', json_decode($result,true));
            }else{
                return api_return('-10682');
            }
        }



        public function setWebProduct($name,$id,$web_id=null){
            $web_id =!empty($web_id)?$web_id:1774;
            $new_array=[
                'pant'=>[
                    'uid'=>0,
                    'web_id'=>$web_id,
                    'title'=>$name.'专属直播',
                    'anchor_id'=>$id,
                    'start_time'=>time(),
                    'status'=>1,
                    'end_time'=>time()+$this->end_time
                ],
                'produt_list'=>[
                    '0'=>'product_b8b4b0e6',
                    '1'=>'product_3a018364',
                    '2'=>'product_cb723f0a',
                    '3'=>'product_b6b43dbd',
                    '4'=>'product_db689004'
                ]
            ];
            return $new_array;
        }


    }



